<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" class="font">
      <el-breadcrumb-item :to="{ path: '/disabled' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- /面包屑 -->

    <!-- 卡片 -->
    <el-card>
      <!-- alert提示信息 -->
      <el-alert
        center
        :closable="false"
        title="添加商品信息"
        type="info"
        show-icon
      >
      </el-alert>

      <!-- Steps 步骤条 -->
      <el-steps
        :space="200"
        :active="active - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab栏标签  左右结构 -->

      <el-form
        label-width="100px"
        label-position="top"
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
      >
        <el-tabs
          v-model="active"
          :tab-position="'left'"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <!-- 商品名称 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>

            <!-- 商品价格 -->
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>

            <!-- 商品重量 -->
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>

            <!-- 商品数量 -->
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>

            <!-- 选择商品分类的级联菜单 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                expandTrigger="hover"
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              :key="item.attr_id"
              v-for="item in manyTableData"
            >
              <!-- 使用数组渲染复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="val"
                  v-for="(val, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品属性 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品图片 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
              :headers="headerObj"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>

          <!-- 商品内容 -->
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" class="btnAdd" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 预览图片对话框 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import { getCateList, paramsgetCateList } from "@/api/commodity";
import { mapGetters } from "vuex";
import { addgoodsL } from "@/api/categories";
import _ from "lodash";
export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {
      active: 0,
      addForm: {
        goods_name: "", //商品名称
        goods_cat: [], // 分类列表
        goods_price: "0", // 价格
        goods_number: "0", // 数量
        goods_weight: "0", // 重量
        //上传图片数组
        pics: [],
        //商品的详情介绍
        goods_introduce: "",
      },

      // 校验规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },

      //用来保存分类数据
      cateList: [],

      // 级联菜单的格式设置
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },

      //动态参数列表
      manyTableData: [],
      //静态属性列表
      onlyTableData: [],

      //上传图片的url地址
      uploadURL: "https://www.liulongbin.top:8888/api/private/v1",

      //保存预览图片的url地址
      previewPath: "",

      // 图片上传的请求头
      headerObj: { Authorization: this.token },

      //控制预览图片对话框的显示和隐藏
      previewVisible: false,
    };
  },
  computed: {
    ...mapGetters(["token"]),
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    },
  },
  watch: {},
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const res = await getCateList();
      // console.log("获取级联菜单:", res);
      this.cateList = res;
    },

    // 级联菜单发生变化4
    handleChange() {
      //   console.log(111);
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
        return;
      }
    },

    // tabs发生切换前调用的钩子函数
    beforeTabLeave(activeName, oldActiveName) {
      //   console.log("tabs发生了变化");
      //   console.log(activeName, oldActiveName);
      //在tab栏切换之前触发，两个形参为切换前，后的tab栏name
      if (oldActiveName === "0") {
        //在第一个标签页的时候
        if (this.addForm.goods_cat.length !== 3) {
          this.$message.error("请选择商品的分类");
          return false;
        } else if (this.addForm.goods_name.trim() === "") {
          this.$message.error("请输入商品名称");
          return false;
        } else if (this.addForm.goods_price.trim() === "0") {
          this.$message.error("请输入商品价格");
          return false;
        } else if (this.addForm.goods_weight.trim() === "0") {
          this.$message.error("请输入商品重量");
          return false;
        } else if (this.addForm.goods_number.trim() === "0") {
          this.$message.error("请输入商品数量");
          return false;
        }
      }
    },

    // tab被选中的标签 tab 实例
    async tabClicked() {
      //   console.log(222);
      if (this.active === "1") {
        try {
          // 发起动态数据
          const res = await paramsgetCateList(this.cateId, "many");
          // console.log("商品参数", res);
          res.forEach((item) => {
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
          });
          this.manyTableData = res;
        } catch (error) {
          console.log(error);
        }
      } else if (this.active === "2") {
        try {
          const data = await paramsgetCateList(this.cateId, "only");
          // console.log("商品属性", data);
          this.onlyTableData = data;
        } catch (error) {
          console.log(error);
        }
      }
    },

    handlePreview(file) {
      console.log("预览时执行:", file);
      //当用户点击图片进行预览时执行，处理图片预览

      this.previewPath = file.url;
      //   //显示预览图片对话框
      this.previewVisible = true;
    },
    handleRemove() {
      // console.log("点击X号删除时执行:", file);
    },
    handleSuccess() {},

    add() {
      // console.log("点击了添加按钮");
      this.$refs.addFormRef.validate(async (isOk) => {
        // console.log("校验通过");
        if (!isOk) return this.$message.error("请填写必要的表单项!");
        const form = _.cloneDeep(this.addForm);
        form.goods_cat = form.goods_cat.join(",");
        console.log(this.manyTableData);
        // console.log(form);
        this.manyTableData.forEach((item) => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          });
        });
        //将onlyTableData（静态属性）处理添加到attrs
        this.onlyTableData.forEach((item) => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          });
        });

        // console.log("99999999999999999999999");

        //发送请求完成商品的添加,商品名称必须是唯一的
        // const res = await this.$http.post("goods", form);
        await addgoodsL(form);
        // console.log("发送请求添加数据:", res);
        this.$message.success("添加商品成功");
        //编程式导航跳转到商品列表
        this.$router.push("/goods");
      });
    },
  },
};
</script>

<style scoped>
.font {
  font-size: 14px;
}
</style>
